
(function () {
  const roleMap = {
    1000000000: 'visitor',
    1000000001: 'superAdmin',
    1000000002: 'teacher',
    1000000003: 'student',
    1000000004: 'guardian',
    1000000005: 'teewonAdmin',
    1000000006: 'regionAdmin',
    1000000007: 'schoolAdmin',
    1000000008: 'developer',
    1000000009: 'headmaster',
    10000000010: 'eduAdmin',
    10000000030: 'systemAdmin'
  }

  function showLoginError () {
    window.$ui.msg({
      type: 'error',
      message: '登录失败!'
    })

    return Promise.reject(new Error('login err'))
  }

  function getUser (token, params) {
    return window.axios({
      method: 'get',
      url: window.$twApp.gateway + '/openapi-uc/uc/getUserByToken/' + token
    }).then((resp) => {
      const user = resp.data.responseEntity

      if (user) {
        user.token = token
        user.role = '1000000000'

        if (user.roleIdList.indexOf('1000000003') !== -1) {
          // 学生
          user.role = '1000000003'
        } else if (user.roleIdList.indexOf('1000000004') !== -1) {
          // 家长
          user.role = '1000000004'
        } else if (user.roleIdList.indexOf('1000000008') !== -1) {
          // 开发者
          user.role = '1000000008'
        } else if (user.roleIdList.indexOf('1000000001') !== -1) {
          // 超级管理员
          user.role = '1000000001'
        } else if (user.roleIdList.indexOf('10000000030') !== -1) {
          // 系统管理员
          user.role = '10000000030'
        } else if (user.roleIdList.indexOf('1000000005') !== -1) {
          // 天闻管理员
          user.role = '1000000005'
        } else if (user.roleIdList.indexOf('10000000010') !== -1) {
          // 教育管理者
          user.role = '10000000010'
        } else if (user.roleIdList.indexOf('1000000006') !== -1) {
          // 区域管理员
          user.role = '1000000006'
        } else if (user.roleIdList.indexOf('1000000007') !== -1) {
          // 学校管理员
          user.role = '1000000007'
        } else if (user.roleIdList.indexOf('1000000009') !== -1) {
          // 校长
          user.role = '1000000009'
        } else if (user.roleIdList.indexOf('1000000002') !== -1) {
          // 教师 - 非区域管理员、学校管理员
          user.role = '1000000002'
        }

        user.roleName = roleMap[user.role]

        if (user.roleId === '1000000003') {
          user.studentId = user.userId
        }

        if (user.roleId === '1000000004') {
          setHeaders(user)
          window.axios.post(window.$twApp.gateway + '/openapi-base/base/getParentInfo', { id: user.userId }).then(resp => {
            if (resp.data.responseEntity) {
              user.studentId = resp.data.responseEntity.studentId
              setUser(user)
            } else {
              return showLoginError()
            }
          })
        } else {
          return setUser(user)
        }
      } else {
        return showLoginError()
      }
    }).catch((e) => {
      if (params.type === 'password') {
        return Promise.reject(e)
      }
    })
  }

  let loginSuccessUrl

  function login (params) {
    loginSuccessUrl = params.loginSuccessUrl
    params.client_id = window.$twApp.appId
    params.client_secret = window.$twApp.appKey

    if (params.type === 'password') {
      params.grant_type = 'password'
      const CryptoJS = window.CryptoJS
      const key = CryptoJS.enc.Utf8.parse(window.$twApp.appKey)

      params.password = CryptoJS.AES.encrypt(params.password, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      }).toString()
    } else {
      params.grant_type = 'client_credentials'
    }

    return window.axios({
      url: window.$twApp.gateway + '/openapi-uc/oauth/token?' + window.$ui.qs.stringify(params, { arrayFormat: 'indices' }),
      method: 'post',
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {}
    }).then((resp) => {
      if (resp.data.access_token) {
        const token = resp.data.access_token
        return getUser(token, params)
      } else {
        return showLoginError(params.type)
      }
    }).catch((err) => {
      if (params.type === 'password') {
        return Promise.reject(err)
      } else {
        if (err.response && err.response.data) {
          window.$ui.msg({
            type: 'error',
            message: err.response.data.errorMesage
          })
        } else {
          return showLoginError(params.type)
        }
      }
    })
  }

  window.$ui.login = login

  function setUser (user) {
    window.$ui.cookie.set('twAppUserId', user.userId)
    window.localStorage.setItem(user.userId, JSON.stringify(user))
    authApp(user)
  }

  function authApp (user) {
    if (window.$pageConfig && window.$pageConfig.roles) {
      const roles = window.$pageConfig.roles.split(',')

      if (roles.length > 0 && roles.indexOf(user.role) === -1) {
        const roleIndex = JSON.parse(window.$siteConfig.roleIndex)
        window.location.href = roleIndex[user.role] || window.$siteConfig.domain
        return
      }
    }

    window.Vue.set(window.$twApp, 'user', user)
    const loginFrom = window.localStorage.getItem('loginFrom')
    setHeaders(user)

    // 如果应用指定了登录后的处理函数，且函数未处理完成，不做下一步操作
    if (typeof window.$twApp.afterLogined === 'function') {
      if (!window.$twApp.afterLogined._done) {
        window.$twApp.afterLogined._user = user
        window.$twApp.afterLogined(user, afterLoginedNext)
        return
      }
    }

    window.$twApp.logged = true

    if (document.querySelector('#app')) {
      window.$lib.mounte()
    } else {
      window.addEventListener('load', function () {
        window.$lib.mounte()
      })
    }

    if (typeof loginSuccessUrl !== 'undefined') {
      const roleIndex = JSON.parse(window.$siteConfig.roleIndex)
      window.location.href = loginSuccessUrl || (window.$twApp.roleHome && window.$twApp.roleHome[user.roleName]) || (roleIndex && roleIndex[user.role]) || window.$twApp.eco.ecoWebServer
    } else if (loginFrom) {
      window.localStorage.removeItem('loginFrom')
      window.location.href = loginFrom
    } else {
      if (window.$ui.urlQuery.accredit_code || window.$ui.urlQuery.token) {
        window.location.hash = '/'
      }
    }

    window.$ui.getAccreditCode()

    setInterval(() => {
      window.$ui.getAccreditCode()
    }, window.$twApp.accreditCodeTime || 1080000)
  }

  function afterLoginedNext (user) {
    window.$twApp.afterLogined._done = true
    window.localStorage.setItem(user.userId, JSON.stringify(user || window.$twApp.afterLogined._user))
    authApp(user || window.$twApp.afterLogined._user)
  }

  function setHeaders (user) {
    window.axios.defaults.headers.common['Access-Token'] = user.token
    window.axios.defaults.headers.common['Current-Org-Id'] = user.orgId
    window.axios.defaults.headers.common['Tenant-Id'] = user.branchCode
    window.axios.defaults.headers.common['X-User-Account'] = user.userId
  }

  function delEcoCookie () {
    window.$ui.cookie.delete('common_access_token')
    window.$ui.cookie.delete('common_user_id')
  }

  function logoff () {
    window.$ui.cookie.delete('twAppUserId')
    delEcoCookie()

    if (window.$twApp.user.userId) {
      window.localStorage.removeItem(window.$twApp.user.userId)
    }

    const loginPage = window.$twApp.loginPage || window.$twApp.eco.loginPage

    if (loginPage) {
      if (typeof loginPage === 'function') {
        loginPage()
      } else {
        window.location.href = loginPage
      }
    }
  }

  window.$twApp.logoff = logoff

  const accreditCode = window.$ui.urlQuery.accredit_code
  const token = window.$ui.urlQuery.token || window.$ui.urlQuery.access_token

  if (token || accreditCode) {
    if (window.$twApp.loginType === 'token') {
      getUser(token, {})
    } else if (window.$twApp.loginType === 'accreditCode') {
      login({ accredit_code: accreditCode })
    } else {
      if (token) {
        getUser(token, {})
      } else if (accreditCode) {
        login({ accredit_code: accreditCode })
      }
    }
  } else {
    if (window.$pageConfig) {
      const twAppUserId = window.$ui.cookie.get('twAppUserId')
      const user = JSON.parse(window.localStorage.getItem(twAppUserId))

      if (twAppUserId && user && (user.userId === twAppUserId)) {
        authApp(user)
      } else if (window.$pageConfig.needLogin === '1') {
        window.localStorage.setItem('loginFrom', window.location.href)
        logoff()
      }
    }
  }
})()
